<--- %%NOBANNER%% --> substrm.sas
 BackForward

/*-------------------<-- Start of Description-->---------------------\
| Similar to %substr;                                                |
| Note: this is a macro function, not a data step function;          |
|---------------------<-- End of Description-->----------------------|
|--------------------------------------------------------------------|
|------------<-- Start of Files or Arguments Needed-->---------------|
| Argument:                                                          |
|    string: the input string;                                       |
|    start: a number, start position;                                |
|           Note: a negative value, will start from the end;         |
|    len: the length of the return string;                           |
|---------------<-- End of Files Arguments Needed-->-----------------|
|--------------------------------------------------------------------|
|------------------<-- Start of Files Created-->---------------------|
|  Example: %put %substrm(1234, 5);                                 |
|           %put %substrm(123456, -2, 4);                           |
|           %put %substrm(12345678, 1, 7);                          |
\-------------------<-- End of Files Created-->---------------------*/
%macro substrm(string, start, len);
/*--------------------------------------------\
| Author:   Duo Zhou;                         |
| Created:  12-28-2001 9:12pm;                |
| Modified: 3-11-2002 9:52pm;                 |
| Purpose:  Substring;                        |
\--------------------------------------------*/
%local length;
%let length=%length(&string);
%if (%quote(&start) eq) %then %do;
   %put ==> Alert! I need a starting position!;
   %goto finish;
%end;
%else %if (%index(%quote(&start),.)) %then %do;
   %put ==> Alert! Starting position must be an integer!;
   %goto finish;
%end;
%if (%index(%quote(&len),.)) %then %do;
   %put ==> Alert! Length of the substring must be an integer!;
   %goto finish;
%end;
%if (0<&length) & (&start<=&length) & (&start>0) %then %do;
   %if %length(&len)=0 %then %substr(&string, &start);
   %else %if (&len>&length-&start+1) %then %substr(&string, &start);
   %else %if (&len>0) %then %substr(&string, &start, &len);
%end;
%else %if (0<&length) & (%sysfunc(abs(&start))<=&length) & (&start<0) %then %do;
   %if %length(&len)=0 %then %substr(&string, 1, %eval(%eval(&length+1)+&start));
   %else %if &len>&length-&start+1 %then %substr(&string, 1, %eval(%eval(&length+1)+&start));
   %else %if &len>0 %then %substr(&string, %eval(%eval(&length+2)+%eval(&start-&len)), &len);
%end;
%finish:
%mend substrm;